// app.js
const constant = require('./utils/constant')
const network = require('./utils/network')
const api = require('./utils/api')
const util = require('./utils/util');
App({
  onLaunch() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    wx.getSystemInfo({
      success: e => {
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.custom = capsule;
          this.globalData.customBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.customBar = e.statusBarHeight + 50;
        }
      }
    })
  },
  verifyLogin() {
    return new Promise((resolve, reject) => {
      var token = wx.getStorageSync(constant.TOKEN)
      if (token) {
        network.get(api.getUserInfo).then((res) => {
          var userInfo = res
          var memberInfo = res.extInfo
          delete userInfo.extInfo
          wx.setStorageSync(constant.USER_INFO, userInfo)
          wx.setStorageSync(constant.MEMBER_INFO, memberInfo)
          resolve()
        }).catch((_) => {
          reject('获取用户信息失败！')
        })
      } else {
        wx.showToast({
          title: '您还未登录，请登录！',
          icon: 'none'
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/user/login/userName/index',
          })
        }, 1000);
        reject('您还未登录，请登录！')
      }
    })

  },
  getUserInfo() {
    return wx.getStorageSync(constant.MEMBER_INFO)
  },
  getOpenId() {
    return new Promise((reslove,reject)=>{
      wx.login({
        success: ({ code}) => {
          network.get(api.code2Session, { code: code }).then(res => {
            reslove(res.openid)
          }).catch(err=>{
            reject(err)
          })
        },
        fail: (err) => {
          util.showToast(err.errMsg)
          reject(err.errMsg)
        }
      })
    })
  },
  api,
  network,
  util,
  constant,
  globalData: {}
})